<template>
  <view class="app">
    <view class="header">
      <!-- 搜索 -->
      <view class="search-box">
        <input
          type="text"
          confirm-type="search"
          v-model="searchKey"
          @confirm="search()"
          class="search-input flex-1"
          placeholder="请输入订单编号搜索"
        />
        <view class="suffix" @click="search()">
          <u-icon size="26" color="#b7b7b7" name="search"></u-icon>
        </view>
      </view>

      <!-- 导航 -->
      <view class="nav-box">
        <view
          class="nav-item"
          v-for="(item, index) in navList"
          :key="index"
          @click="changeOrderStatus(item.status)"
        >
          <text class="nav-text" :class="{ 'nav-item-active': item.status == orderStatus }">
            {{ item.label }}
          </text>
        </view>
      </view>
    </view>

    <view class="main">
      <z-paging
        ref="paging"
        v-model="orderList"
        :default-page-size="limit"
        :use-page-scroll="true"
        :to-bottom-loading-more-enabled="true"
        :auto="false"
        :fixed="false"
        :min-delay="600"
        :show-loading-more-no-more-view="false"
        :refresher-enabled="false"
        :auto-hide-loading-after-first-loaded="false"
        @query="getData"
      >
        <view class="order-item" v-for="(order, index) in orderList" :key="index">
          <view class="order-content" @click="gotoDetail(order.order_no)">
            <view class="order-header">
              <text class="order-no">订单编号：{{ order.order_no }}</text>
              <text>{{ navStatus[order.status] }}</text>
            </view>
            <view class="goods-item" v-for="(goods, idx) in order.order_goods" :key="idx">
              <view class="item-left">
                <view class="goods-logo">
                  <image :src="goods.goods_logo"></image>
                </view>
              </view>
              <view class="item-right">
                <view class="goods-name line-1">{{ goods.goods_name }}</view>
                <view class="desc-box" v-if="goods.goods_desc">
                  <text class="line-2">{{ goods.goods_desc }}</text>
                </view>
                <view class="goods-bottom">
                  <text class="goods-price">{{ goods.goods_price }}</text>
                  <text class="goods-num">{{ goods.goods_num }}</text>
                </view>
              </view>
            </view>
            <view class="amount">
              <text>应付款：</text>
              <text class="pay-price">{{ order.real_price }}</text>
            </view>
          </view>

          <view class="order-footer" v-if="order.status == 10">
            <view class="action">
              <text class="btn cancel-btn mr-2" @click="cancel(order)">取消</text>
              <text class="btn pay-btn" @click="wxpay(order)">付款</text>
            </view>
          </view>

          <view class="order-footer" v-else-if="order.status >= 40">
            <view class="action">
              <text class="btn logistics-btn" @click="logistics(order)">查看物流</text>
              <text class="btn sign-btn ml-2" @click="sign(order)" v-if="order.status == 40">签收</text>
            </view>
          </view>
        </view>

        <template #loading>
          <view class="loading">
            <mt-logo-loading :size="88"></mt-logo-loading>
          </view>
        </template>
      </z-paging>
    </view>

    <!-- 物流信息 -->
    <u-popup v-model="showWin" border-radius="20" mode="bottom" :mask-close-able="false" height="70%">
      <view class="popup-container">
        <view v-if="!loading">
          <view class="popup-header">
            <view class="popup-title">
              <text>物流信息</text>
              <view class="close-btn" @click="showWin = false">
                <u-icon custom-prefix="mt-icon" name="close-bold" color="black" size="20"></u-icon>
              </view>
            </view>
            <view class="express-info">
              <view class="flex items-center">
                <view class="express-logo">
                  <image
                    mode="widthFix"
                    @error="expressInfo.express_logo = '/static/icon/img/express/package.png'"
                    :src="expressInfo.express_logo"
                  />
                </view>
                <text class="mr-2">{{ expressInfo.express_name }}</text>
                <text>{{ expressInfo.express_no }}</text>
              </view>
              <text class="copy-btn" @click="copyExpressNo()">复制</text>
            </view>
          </view>

          <view class="express-time-line">
            <u-time-line>
              <u-time-line-item v-for="(item, index) in logisticsList" :key="index">
                <template #node>
                  <view :class="index == 0 ? 'time-line-node-large' : 'time-line-node-small'"></view>
                </template>
                <template #content>
                  <view>
                    <view class="time-line-time">{{ formatTime(item.time) }}</view>
                    <view class="time-line-desc">{{ item.context }}</view>
                  </view>
                </template>
              </u-time-line-item>
            </u-time-line>
          </view>
          <view class="express-address">
            <view class="address-left">
              <image mode="aspectFit" src="/static/icon/svg/address/location.svg" />
            </view>
            <view class="address-right">
              <view class="address-title">
                <view class="address-receiver">
                  <text class="mr-20rpx">{{ expressInfo.receiver }}</text>
                  <text>{{ expressInfo.phone }}</text>
                </view>
              </view>
              <view class="address-detail">
                <text>
                  {{ expressInfo.province }} {{ expressInfo.city }} {{ expressInfo.area }}
                  {{ expressInfo.address }}
                </text>
              </view>
            </view>
          </view>
        </view>
        <view class="flex flex-col justify-center flex-1" v-else>
          <mt-logo-loading :size="88"></mt-logo-loading>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts" setup>
  import MtLogoLoading from '@/components/mt-loading/mt-logo-loading.vue';
  import { ref, nextTick, watch } from 'vue';
  import {
    getOrder as getDataApi,
    cancelOrder,
    wxpayOrder,
    signOrder,
    getExpress,
    traceLogistics,
  } from '@/api/goods/order';
  import { onLoad, onReachBottom } from '@dcloudio/uni-app';
  import { report } from '@/utils/exception';
  import { msg } from '@/utils/msg';
  import type { OrderItem, OrderExpress, OrderExpressLogistics } from '@/types/order';

  const searchKey = ref<string>('');
  const limit = 10;
  const orderList = ref<OrderItem[]>([]);
  const paging = ref();
  const orderStatus = ref<number>(-1);
  const showWin = ref<boolean>(false);
  const loading = ref<boolean>(false);
  const expressInfo = ref<OrderExpress>({} as OrderExpress);
  const logisticsList = ref<OrderExpressLogistics[]>([]);

  const navList = [
    { label: '全部', status: -1 },
    { label: '待付款', status: 10 },
    // { label: '待审核', status: 20 },
    { label: '待发货', status: 30 },
    { label: '待收货', status: 40 },
    // { label: '退款', status: 51 },
    { label: '售后', status: 72 },
    // { label: '已完成', status: 70 },
  ];

  const navStatus: string[] = [];
  navStatus[0] = '已取消';
  navStatus[10] = '待付款';
  navStatus[20] = '待审核';
  navStatus[22] = '审核拒绝';
  navStatus[30] = '待发货';
  navStatus[40] = '待收货';
  navStatus[50] = '申请退款';
  navStatus[51] = '已退款';
  navStatus[52] = '退款失败';
  navStatus[70] = '已完成';

  const getData = (pageNo: number, pageSize: number) => {
    getDataApi(pageNo, pageSize, orderStatus.value, searchKey.value)
      .then((res) => {
        paging.value.complete(res.data.list);
      })
      .catch((err) => {
        report(err);
      });
  };

  onReachBottom(() => {
    paging.value.doLoadMore();
  });

  onLoad((option: any) => {
    if (option.status) {
      orderStatus.value = option.status;
    }
    nextTick(() => {
      paging.value.reload();
    });
  });

  // 搜索
  let searchKeyTemp = '';
  const search = () => {
    if (searchKey.value == searchKeyTemp) return false;
    searchKeyTemp = searchKey.value;
    paging.value.reload();
  };

  // 切换订单状态
  const changeOrderStatus = (status: number) => {
    if (orderStatus.value == status) return;
    orderStatus.value = status;
    searchKey.value = '';
    searchKeyTemp = '';
    paging.value.reload();
  };

  // 订单取消
  const cancel = (order: OrderItem) => {
    msg.confirm('确定要取消该订单？', () => {
      msg.loading();
      cancelOrder(order.order_no)
        .then((res) => {
          order.status = 0;
          msg.success('订单取消成功');
        })
        .catch((err) => {
          report(err);
        });
    });
  };

  // 微信支付
  const wxpay = (order: OrderItem) => {
    msg.loading('支付中');
    wxpayOrder(order.order_no)
      .then((resp) => {
        uni.requestPayment({
          provider: 'wxpay',
          orderInfo: '', // 微信支付可以为空
          timeStamp: resp.data.timeStamp, // 时间戳（单位：秒）
          nonceStr: resp.data.nonceStr, // 随机字符串
          package: resp.data.package, // 带有预支付prepay_id参数
          signType: resp.data.signType, // 签名类型
          paySign: resp.data.paySign, // 支付签名
          success: function (res) {
            msg.success('支付成功');
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/order/index?status=30' });
            }, 2000);
          },
          fail: function (err) {
            uni.hideLoading();
            uni.navigateTo({ url: '/pages/order/detail?order_no=' + order.order_no });
          },
        });
      })
      .catch((err) => {
        report(err);
      });
  };

  // 物流追踪
  const logistics = (order: OrderItem) => {
    showWin.value = true;
    loading.value = true;

    getExpress(order.order_no)
      .then((res) => {
        expressInfo.value = res.data;
        expressInfo.value.express_logo = `/static/icon/img/express/${expressInfo.value.express_code}.png`;
        traceLogistics(order.order_no, expressInfo.value.express_no, expressInfo.value.express_code)
          .then((res) => {
            logisticsList.value = res.data.logistics;
            if (order.status == 40 && res.data.is_sign == 1) {
              order.status = 70;
            }
            setTimeout(() => {
              loading.value = false;
            }, 600);
          })
          .catch((err) => {
            report(err);
          });
      })
      .catch((err) => {
        report(err);
      });
  };

  // const bodyStyle = document.body.style;
  // watch(
  //   () => showWin.value,
  //   () => {
  //     bodyStyle.overflow = showWin.value ? 'hidden' : 'auto';
  //   }
  // );

  const formatTime = (date: string) => {
    return date.substring(5, 16);
  };

  const copyExpressNo = () => {
    uni.setClipboardData({
      data: expressInfo.value.express_no,
    });
  };

  // 订单签收
  const sign = (order: OrderItem) => {
    msg.confirm('确定要签收该订单？', () => {
      msg.loading();
      signOrder(order.order_no)
        .then((res) => {
          order.status = 70;
          msg.success('订单签收成功');
        })
        .catch((err) => {
          report(err);
        });
    });
  };

  const gotoDetail = (order_no: string) => {
    uni.navigateTo({ url: `/pages/order/detail?order_no=${order_no}` });
  };
</script>

<style lang="scss" scoped>
  .header {
    position: fixed;
    width: 100%;
    z-index: 12;
    background: white;
    box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 10px;

    .search-box {
      display: flex;
      justify-content: center;
      background: #f5f5f5;
      margin: 10rpx 30rpx 30rpx;
      padding: 12rpx 30rpx;
      border-radius: 100rpx;

      .search-input {
        font-size: 26rpx;
        color: #9f9f9f;
      }

      .suffix {
        padding-left: 15rpx;
        justify-content: center;
      }
    }

    .nav-box {
      display: flex;
      align-items: center;
      font-size: 30rpx;

      .nav-item {
        width: 20%;
        display: flex;
        align-items: center;
        justify-content: center;

        .nav-text {
          position: relative;
          width: 90rpx;
          text-align: center;
          padding-bottom: 25rpx;
        }
      }

      .nav-item-active {
        &:before {
          content: '';
          position: absolute;
          right: 0;
          bottom: 0;
          left: 0;
          height: 6rpx;
          background: $themeColor;
          border-radius: 10rpx;
        }
      }
    }
  }

  .main {
    padding: 180rpx 25rpx 20rpx;

    .order-item {
      background: #ffffff;
      padding: 28rpx 0 20rpx;
      margin-bottom: 20rpx;
      border-radius: 20rpx;
      font-size: 28rpx;

      .order-content {
        padding: 0 25rpx;

        .order-header {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .order-no {
            font-size: 28rpx;
          }
        }
        .goods-item {
          padding: 25rpx 0 20rpx;
          display: flex;
          align-items: start;

          .item-left {
            display: flex;
            align-items: center;

            .goods-logo {
              margin-left: 5rpx;
              margin-right: 20rpx;

              image {
                width: 150rpx;
                height: 150rpx;
                border-radius: 20rpx;
              }
            }
          }

          .item-right {
            flex: 1;

            .goods-name {
              font-size: 30rpx;
              font-weight: 600;
              // max-width: 470rpx;
            }
            .desc-box {
              padding: 10rpx 15rpx;
              background: #f5f5f5;
              margin-top: 10rpx;
              font-size: 24rpx;
              color: #949494;
              border-radius: 10rpx;
            }

            .goods-bottom {
              margin-top: 20rpx;
              display: flex;
              align-items: baseline;
              justify-content: flex-end;

              .goods-price {
                font-size: 30rpx;

                &::before {
                  content: '￥';
                  font-size: 22rpx;
                }
              }
              .goods-num {
                font-size: 26rpx;

                &::before {
                  content: 'x ';
                  margin: 0 2rpx 0 10rpx;
                  font-size: 22rpx;
                }
              }
            }
          }
        }
        .amount {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          padding-bottom: 25rpx;

          .pay-price {
            font-size: 30rpx;
            font-weight: 600;

            &::before {
              content: '￥';
              font-size: 22rpx;
            }
          }
        }
      }

      .order-footer {
        padding: 20rpx 25rpx 0;
        border-top: 1rpx solid #f5f5f5;

        .action {
          display: flex;
          align-items: center;
          justify-content: flex-end;

          .btn {
            display: flex;
            flex: none;
            align-items: center;
            justify-content: center;
            width: 120rpx;
            font-size: 24rpx;
            padding: 12rpx 0;
            border-radius: 50rpx;
            letter-spacing: 1rpx;
          }

          .cancel-btn,
          .logistics-btn {
            border: 1rpx solid #c4c4c4;
          }

          .pay-btn {
            color: white;
            background-image: linear-gradient(to right, #f3204f, #f33720);
            box-shadow: rgba(255, 28, 0, 0.2) 0 5rpx 12rpx;
          }

          .sign-btn {
            color: white;
            background-image: linear-gradient(to right, #2913f3, #2066f3);
            box-shadow: rgba(15, 114, 244, 0.2) 0 5rpx 12rpx;
          }

          .logistics-btn {
            width: 150rpx;
          }
        }
      }
    }

    .loading {
      display: flex;
      flex-direction: column;
      justify-content: center;
      height: 900rpx;
    }
  }

  .popup-container {
    display: flex;
    flex-direction: column;
    padding: 0rpx 25rpx 30rpx;
    min-height: 100%;
    background: #f2f2f2;

    .popup-header {
      position: sticky;
      top: 0;
      z-index: 99;
      background: #f2f2f2;
    }

    .popup-title {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      font-weight: 600;
      height: 95rpx;

      .close-btn {
        position: absolute;
        top: 22rpx;
        right: 5rpx;
        padding: 14rpx;
        display: flex;
        border-radius: 50%;
        background: #e2e2e2;
      }
    }

    .express-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 29rpx;
      height: 75rpx;
      background: white;
      border-top-left-radius: 20rpx;
      border-top-right-radius: 20rpx;
      border-bottom: 1rpx solid #f2f2f2;

      .express-logo {
        width: 50rpx;
        height: 50rpx;
        margin-left: 15rpx;
        margin-right: 12rpx;

        image {
          width: 100%;
        }
      }

      .copy-btn {
        padding: 15rpx 20rpx 15rpx 15rpx;
      }
    }

    .express-time-line {
      background: white;
      padding: 20rpx 40rpx 5rpx;

      .time-line-node-large {
        width: 25rpx;
        height: 25rpx;
        border-radius: 50%;
        background: $themeColor;
      }

      .time-line-node-small {
        width: 20rpx;
        height: 20rpx;
        border-radius: 50%;
        background: #c3c3c3;
      }

      .time-line-time {
        color: #353535;
        font-size: 32rpx;
        font-weight: 600;
        margin-bottom: 5rpx;
      }

      .time-line-desc {
        color: #6e6e6e;
        font-size: 27rpx;
        margin-bottom: 6rpx;
      }
    }

    .express-address {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30rpx 20rpx;
      background: white;
      font-size: 29rpx;
      border-bottom-left-radius: 20rpx;
      border-bottom-right-radius: 20rpx;
      border-top: 1rpx solid #f2f2f2;

      .address-left {
        margin-right: 9rpx;
        position: relative;

        image {
          width: 42rpx;
          height: 42rpx;
        }
      }

      .address-right {
        flex: 1;

        .address-title {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10rpx;

          .address-receiver {
            display: flex;
            font-size: 32rpx;
            font-weight: 600;
          }

          .edit-btn {
            color: #9a9a9a;
            font-size: 24rpx;
            padding: 4rpx 12rpx;
            border-radius: 50rpx;
            border: 1rpx solid #9a9a9a;
          }
        }

        .address-detail {
          display: flex;
          color: #757575;
          font-size: 28rpx;
        }
      }
    }
  }

  :deep(.u-time-axis) {
    padding-left: 28rpx;
  }
  :deep(.u-time-axis-node) {
    left: -28rpx;
    top: 8rpx;
  }
</style>
